package com.dasnzhuang.halo.security.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.dasnzhuang.halo.security.entity.SysRole;
import com.dasnzhuang.halo.security.entity.SysUser;
import com.dasnzhuang.halo.security.service.UserService;

@Component
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired  // 业务服务类
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // SysUser对应数据库中的用户表，是最终存储用户和密码的表，可自定义
        // 本例使用SysUser中的name作为用户名:
        SysUser user = userService.findByName(userName);
        if (user == null) { throw new UsernameNotFoundException("UserName " + userName + " not found"); }
        // SecurityUser实现UserDetails并将SysUser的name映射为username
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        Set<SysRole> userRoles = user.getSysRoles();
        authorities.add(new SimpleGrantedAuthority("USER"));
        if (userRoles != null) {
            for (SysRole role : userRoles) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getName());
                authorities.add(authority);
            }
        }
        User suser = new User(user.getName(), user.getPassword(), authorities);
        return suser;
    }

}
